﻿namespace ModuleOne
{
    using System;
    using System.Windows;

    using MEF_Test.Bricks;
    using MEF_Test.Bricks.TemplateProvider;
    using MEF_Test.Contracts;

    public class LocalDiskBrowserNodeViewModelFactory : IDiskBrowserNodeViewModelFactory
    {
        /// <summary>
        /// The factory to use to instanciate Browser Detail View Models.
        /// </summary>
        private readonly IBrowserDetailViewModelFactory _browserDetailViewModelFactory;

        /// <summary>
        /// Initializes a new instance of the <see cref="LocalDiskBrowserNodeViewModelFactory"/> class.
        /// </summary>
        /// <param name="browserDetailViewModelFactory">The browser detail view model factory.</param>
        public LocalDiskBrowserNodeViewModelFactory(IBrowserDetailViewModelFactory browserDetailViewModelFactory)
        {
            _browserDetailViewModelFactory = browserDetailViewModelFactory;
        }

        /// <summary>
        /// Creates a Browser Node View Model according to the provided dependencies.
        /// </summary>
        /// <param name="fileHandler">The file handler.</param>
        /// <param name="mediaHandlerFactoryProvider">The media handler factory provider.</param>
        /// <param name="templateProvider">The template provider.</param>
        /// <returns>A valid browser view model representing a media file.</returns>
        public BrowserNodeViewModel<IDiskFileHandler> Create(IDiskFileHandler fileHandler, IMediaHandlerFactoryProvider mediaHandlerFactoryProvider, ITemplateProvider templateProvider)
        {
            // Create a proper MediaHandler
            IMediaHandlerFactory mediaHandlerFactory = mediaHandlerFactoryProvider.GetMediaHandlerFactory(fileHandler);

            if (mediaHandlerFactory == null)
            {
                string message = string.Format(
                    "No media handler factory export found for \ncontent type {0}\nfile {1} ",
                    fileHandler.ContentType,
                    fileHandler.Path);
                throw new InvalidOperationException(message);
            }

            // let's return a BrowserNode.
            string templateKind = "BrowserItem.Disk.Media." + fileHandler.ContentType;
            string detailTemplateKind = "BrowserItem.Disk.Media.Detail." + fileHandler.ContentType;

            DataTemplate dataTemplate = templateProvider.GetTemplate(templateKind);
            DataTemplate detailDataTemplate = templateProvider.GetTemplate(detailTemplateKind);
            var mediaHandler = mediaHandlerFactory.Create(fileHandler);

            var node = new BrowserNodeViewModel<IDiskFileHandler>(fileHandler, mediaHandler, dataTemplate, detailDataTemplate, _browserDetailViewModelFactory);

            return node;
        }
    }
}